const { ipcMain } = require('electron');
const { searchBili, getBiliAudioStreaming, getAudioCid, getAudioStreamingUrl, searchMenu, getMenuInfo, getMenuList } = require('../api/bilibili');

ipcMain.handle('biliTypeSearch', async ($event, keyword, currentPage) => {
  try {
    const { data } = await searchBili(keyword, currentPage);
    if (data.code !== 0) {
      console.log('B站搜索失败', data.message);
      return {};
    } else {
      const filterResults = data.data.result.map((item) => {
        return {
          platform: 'bili',
          bvid: item.bvid,
          title: item.title,
          author: item.author,
          link: item.arcurl,
          pic: item.pic,
        };
      });
      const res = {
        page: data.data.page,
        pagesize: data.data.pagesize,
        numResults: data.data.numResults,
        numPages: data.data.numPages,
        result: filterResults,
      };
      return res;
    }
  } catch (error) {
    console.log('B站搜索失败', error);
  }
});

ipcMain.handle('getSongStreamUrl', async ($event, songInfo) => {
  const res1 = await getAudioCid(songInfo.bvid);
  const cid = res1.data.data.cid;
  const res2 = await getAudioStreamingUrl(songInfo.bvid, cid);
  const songStreamingUrl = res2.data.data.dash.audio[0].baseUrl;
  return songStreamingUrl;
});

ipcMain.handle('getBiliAudio', async ($event, url) => {
  const res = await getBiliAudioStreaming(url);
  return res.data;
});

ipcMain.handle('getSongStream', async ($event, songInfo) => {
  const res1 = await getAudioCid(songInfo.bvid);
  const cid = res1.data.data.cid;
  const res2 = await getAudioStreamingUrl(songInfo.bvid, cid);
  const songStreamingUrl = res2.data.data.dash.audio[0].baseUrl;
  const res3 = await getBiliAudioStreaming(songStreamingUrl);
  return res3.data;
});

ipcMain.handle('searchMenu', async ($event, currentPage) => {
  const res = await searchMenu(currentPage);
  return res.data.data;
});

ipcMain.handle('getMenuInfo', async ($event, params) => {
  const res1 = await getMenuInfo(params.sid);
  const { title, cover, intro, uname, menuId } = res1.data.data;
  const res2 = await getMenuList(params);
  return {
    title,
    cover,
    intro,
    uname,
    menuId,
    songListInfo: res2.data.data,
  };
});
